package Component

import (
	"bufio"
	"fmt"
	"golang.org/x/crypto/ssh"
	"time"
)

type RemoteShellComponent struct {
	remoteServer string
	currentDir   string
	cmd          string

	userName string
	password string
}

func (self *RemoteShellComponent) Run() (err error) {
	sshConfig := &ssh.ClientConfig{
		User: self.userName,
		Auth: []ssh.AuthMethod{
			ssh.Password(self.password),
		},
		HostKeyCallback: ssh.InsecureIgnoreHostKey(),
		ClientVersion:   "",
		Timeout:         10 * time.Second,
	}

	sshClient, err := ssh.Dial("tcp", self.remoteServer, sshConfig)
	if err != nil {
		return
	}
	defer sshClient.Close()

	session, err := sshClient.NewSession()
	if err != nil {
		return
	}
	defer session.Close()

	cmd := self.cmd
	if self.currentDir != "" {
		cmd = fmt.Sprintf("cd %s;%s", self.currentDir, self.cmd)
	}

	fmt.Println(self.cmd)

	piper, _ := session.StdoutPipe()
	piperErr, _ := session.StderrPipe()
	err = session.Start(cmd)

	if err != nil {
		return
	}

	in := bufio.NewScanner(piper)
	for in.Scan() {
		cmdRe:=ConvertByte2String(in.Bytes(),UTF8)
		fmt.Println(cmdRe)
	}

	inErr := bufio.NewScanner(piperErr)
	for inErr.Scan() {
		cmdRe:=ConvertByte2String(inErr.Bytes(),UTF8)
		fmt.Println(cmdRe)
	}
	session.Wait()

	return
}

func (self *RemoteShellComponent) SetParameter(name string, parameter string) {
	if name == UserName {
		self.userName = parameter
	} else if name == PassWord {
		self.password = parameter
	} else if name == RmoteServer {
		self.remoteServer = parameter
	} else if name == CMD {
		self.cmd = parameter
	} else if name == RemoteCurrentDir {
		self.currentDir = parameter
	}
}
